<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" height="600px" width="1200px" @open="open" @close="close" :append-to-body="true">
    <el-switch v-show="true" class="switch" v-model="ifEditMode" active-text="编辑模式" inactive-text="查看模式"> </el-switch>
    <div class="contain-div" v-show="ifEditMode">
      <el-row>
        <el-button type="text" icon="el-icon-circle-plus-outline" @click="addWeek" style="margin-left: 0px">新增</el-button>
      </el-row>
      <el-scrollbar class="week-container">
        <el-row>
          <div v-for="(weekItem, index) in weekList" :key="index">
            <el-col :span="12" class="week-col">
              <mpm-week-picker :ref="'week' + index" v-model="weekItem.week" type="week" @input="setValue($event, index)" :format="weekTemplate(index)" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="{ firstDayOfWeek: 7 }" placeholder="选择周" style="width: 320px;"></mpm-week-picker>
              <el-button type="text" icon="el-icon-remove-outline" @click="deleteWeek(index)" class="deleteButton">删除</el-button>
            </el-col>
          </div>
        </el-row>
      </el-scrollbar>
      <el-row class="button-row">
        <el-button type="primary" style="float: right" @click="doSubmit" :loading="saveLoading"> <svg-icon icon-class="save" />保存</el-button>
      </el-row>
    </div>
    <div class="contain-div" v-show="!ifEditMode">
      <el-row class="show-row" v-for="(showItem, index) in showList" :key="index">
        <el-col :span="2" class="year-col">
          <span class="year-span">年份</span><el-tag>{{ showItem.year }}</el-tag>
        </el-col>
        <el-col :span="2"><div style="margin-top:4px;">不统计周</div></el-col>
        <el-col :span="1" class="week-col" v-for="(weekItem, index) in showItem.weekList" :key="index">
          <el-tag>{{ weekItem }}</el-tag>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_edit } from '@tapui/mixins/mixin_edit'
/** 子组件 */
import MpmWeekPicker from './MpmWeekPicker/index'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate, getWeekNumber } from 'element-ui/src/utils/date-util'
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { MpmWeekPicker },
  data() {
    this.formatDate = formatDate
    return {
      moduleTitle: '周配置功能',
      title: '周配置',
      ifEditMode: false,
      url: {
        // 额外的url
        saveMeetWeek: 'mpm/projectNoMeetWeek/saveNoMeetWeek',
        getMeetWeek: 'mpm/projectNoMeetWeek/list'
      },
      weekList: [{ yearNumber: '', weekNumber: '', week: '', weekStart: '', weekEnd: '' }],
      // 展示用数据结构
      showList: []
    }
  },
  watch: {
    weekList: {
      handler(value, oldvalue) {
        this.getShowList()
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    // 返回选择的所有年份
    selectYearList() {
      let resultYearList = []
      for (let item of this.weekList) {
        item.yearNumber ? resultYearList.push(Number(item.yearNumber)) : null
      }
      let set = new Set(resultYearList)
      return [...set].sort(this.sortMethod)
    }
  },
  methods: {
    // 返回某一年份选择的所有周
    getWeekOfYear(year) {
      let resultWeekList = []
      for (let item of this.weekList) {
        Number(item.yearNumber) === year ? resultWeekList.push(Number(item.weekNumber)) : null
      }
      return resultWeekList.sort(this.sortMethod)
    },
    // 展示用数据结构构造
    getShowList() {
      let result = []
      for (let item of this.selectYearList) {
        let showItem = {}
        showItem.year = item
        showItem.weekList = this.getWeekOfYear(item)
        result.push(showItem)
      }
      this.showList = result
    },
    /** 页面打开时执行*/
    open() {
      this.saveLoading = true
      getAction(this.url.getMeetWeek).then((res) => {
        if (res.success) {
          let resultList = this.getAdapter(res.result.dataList)
          resultList = resultList.sort(this.sortWeek)
          this.weekList = resultList
        } else {
          this.$tap.alert('获取周配置信息失败，请联系管理员', 'warning')
        }
        this.saveLoading = false
      })
    },
    setValue(val, index) {
      this.$set(this.weekList[index], 'week', val)
      // 获取当前周数对应的时间
      const currentDate = new Date(val)
      // 设置本周开始时间
      const start = currentDate.getDate() - currentDate.getDay() + 1
      const startDate = new Date(currentDate.setDate(start))
      // 设置本周结束时间
      const endDate = new Date(startDate.getTime() + 7 * 24 * 60 * 60 * 1000 - 1)
      // 设置数字年份标识
      const yearNumber = String(currentDate.getFullYear())
      // 设置数字周标识
      const weekNumber = String(getWeekNumber(currentDate))
      // 判断是否存在相同数据
      let ifSame = this.weekList.some((item) => {
        return item.weekNumber === weekNumber && item.yearNumber === yearNumber
      })
      if (ifSame) {
        this.$tap.message('已存在相同的周，禁止重复选择', 'warning')
        this.$set(this.weekList[index], 'week', '')
      } else {
        this.$set(this.weekList[index], 'weekStart', formatDate(startDate, 'yyyy-MM-dd HH:mm:ss'))
        this.$set(this.weekList[index], 'weekEnd', formatDate(endDate, 'yyyy-MM-dd HH:mm:ss'))
        this.$set(this.weekList[index], 'weekNumber', weekNumber)
        this.$set(this.weekList[index], 'yearNumber', yearNumber)
      }
    },
    // 周数显示模板
    weekTemplate(index) {
      let range = ''
      if (this.weekList[index].weekStart && this.weekList[index].weekEnd) {
        const start = new Date(this.weekList[index].weekStart)
        const end = new Date(this.weekList[index].weekEnd)
        range = `（${formatDate(start, 'MM月dd日')}-${formatDate(end, 'MM月dd日')}）`
      }
      return `yyyy年第WW周${range}`
    },
    deleteWeek(index) {
      this.weekList.splice(index, 1)
    },
    addWeek() {
      this.weekList.push({ week: '', weekStart: '', weekEnd: '' })
    },
    // 传递数据适配
    saveAdapter(listData) {
      let resultList = []
      for (let item of listData) {
        let bridge = {}
        bridge.meetyear = item.yearNumber
        bridge.meetweek = item.weekNumber
        bridge.meetbegindate = item.weekStart
        bridge.meetenddate = item.weekEnd
        bridge.meetweekdate = item.week
        resultList.push(bridge)
      }
      return resultList
    },
    // 获取数据适配
    getAdapter(listData) {
      let resultList = []
      for (let item of listData) {
        let bridge = {}
        bridge.yearNumber = item.meetyear
        bridge.weekNumber = item.meetweek
        bridge.weekStart = item.meetbegindate
        bridge.weekEnd = item.meetenddate
        bridge.week = item.meetweekdate
        resultList.push(bridge)
      }
      return resultList
    },
    // 数组排序方法
    sortWeek(item1, item2) {
      let year1 = Number(item1.yearNumber)
      let year2 = Number(item2.yearNumber)
      let week1 = Number(item1.weekNumber)
      let week2 = Number(item2.weekNumber)
      if (year1 > year2) {
        return -1
      } else if (year1 < year2) {
        return 1
      } else {
        return week1 > week2 ? -1 : 1
      }
    },
    sortMethod(item1, item2) {
      return item1 > item2 ? -1 : 1
    },
    doSubmit() {
      this.saveLoading = true
      // 保存前过滤掉空值
      let noNllList = this.weekList.filter((item) => {
        return item.week !== ''
      })
      let paramList = this.saveAdapter(noNllList)
      let param = {}
      param.weeklist = paramList
      postAction(this.url.saveMeetWeek, param).then((res) => {
        if (res.success) {
          this.$tap.message('修改成功', 'success')
          //   this.visible = false
        } else {
          this.$tap.alert('修改失败，请联系管理员', 'warning')
        }
        this.saveLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.button-row {
  margin-top: 5px;
}
.week-col {
  margin-bottom: 10px;
}
.el-scrollbar {
  height: 450px;
}
/deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
}
.show-row {
  margin-top: 15px;
}
.year-col {
  margin-right: 10px;
}
.year-span {
  margin-right: 10px;
}
.contain-div {
  height: 550px;
}
.switch {
  margin-left: 0px;
}
</style>
